import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TimerTask;

/**
 * 游戏启动类
 */
public class MainGame {
    enum Game_mode{
        RUNNING_MODE,
        BUILDING_MODE
    }

    public static void main(String[] args) {
        ApplicationWindow frame = new ApplicationWindow();

        // the following code realizes the top level application window
        frame.pack();
        frame.setVisible(true);
    }


    /**
     * Overview: An ApplicationWindow is a top level program window that 
     * contains two toolbar and an animation window.
     * 游戏主窗口
     */
    private static class ApplicationWindow extends JFrame {

        private static final long serialVersionUID = 3257563992905298229L;
        final static int SCREEN_WIDTH = 800;
        final static int SCREEN_HEIGHT = 600;

        protected AnimationWindow animationWindow;

        JToolBar menuBar;
        JToolBar gizmoBar;
        JToolBar operationBar;
        JButton button = null;
        JButton runButton = null;//用于暂停/继续按钮

        Box posBox;         //for showing/editing position
        JLabel posLabel;
        JTextField posX;
        JTextField posY;

        Box rateBox;       //for showing/editing rate
        JLabel rateLabel;
        JTextField rateX;
        JTextField rateY;

        private Gizmos oldChoosedGizmos = null;

        /**
         * @effects Initializes the application window so that it contains
         * a toolbar and an animation window.
         */
        public ApplicationWindow() {

            // Title bar
            super("GizmosBall 429 a_0.4.0");

            // respond to the window system asking us to quit
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });



            //Create the menuBar.上方的工具栏，包括模式切换等功能
            menuBar = new JToolBar();
            addButtons(menuBar);     //添加工具栏中的button
            posBox.setVisible(false);//posBox and rateBox is invisible in default
            rateBox.setVisible(false);


            //Create the gizmoBar.左侧工具栏，主要提供图形添加
            gizmoBar = new JToolBar(SwingConstants.VERTICAL);
            addTools(gizmoBar);        //添加工具栏中的button
            gizmoBar.setVisible(false);//only show when editing

            //Create the operationBar.右侧工具栏，主要提供对物件的操作。
            operationBar=new JToolBar(SwingConstants.VERTICAL);
            addOperations(operationBar);
            //only show when editing and gizmo/ball is choson
            //operationBar.setVisible(false);


            //Create the animation area used for output.动画窗口，负责图形绘制
            animationWindow = new AnimationWindow();
            // Put it in a scrollPane, (this makes a border)
            JScrollPane scrollPane = new JScrollPane(animationWindow);


            //Lay out the content pane.

            JPanel contentPane = new JPanel() ;
            contentPane.setLayout(new BorderLayout());
            contentPane.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
            contentPane.add(menuBar, BorderLayout.NORTH);
            contentPane.add(gizmoBar, BorderLayout.WEST);
            contentPane.add(operationBar, BorderLayout.EAST);
            contentPane.add(scrollPane, BorderLayout.CENTER);
            setContentPane(contentPane);

            TimerTask task = new TimerTask() {
                public void run() {
                    Gizmos currentGizmos = animationWindow.getCurrentChoosedGizmos();
                    if(currentGizmos!=null && currentGizmos != oldChoosedGizmos){
                        oldChoosedGizmos = currentGizmos;
                        System.out.println("nowShowGizmos"+currentGizmos.getGizmosID());
                        /**
                         * 此计时器不断从animationWindow中取出当前选中的小物件
                         * oldChoosedGizmos就是当前选中的物件
                         * 请@杨芯芯 把修改参数的操作加上
                         */
                        operationBar.setVisible(true);
                    }
                }
            };
            java.util.Timer timer = new java.util.Timer(true);
            timer.schedule(task,0,100);
        }

        /**
         * @modifies toolBar 
         * @effects adds Run, Stop and Quit buttons to toolBar
         * @param toolBar toolbar to add buttons to.
         */
        protected void addButtons(JToolBar toolBar) {

            toolBar.setBorderPainted(false);
            toolBar.setBackground(Color.LIGHT_GRAY);

            JButton button = null;

            button = new JButton("  保存配置  ");
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setToolTipText("保存游戏");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    saveGame();
                }
            });
            toolBar.add(button);


            button = new JButton("  导入配置  ");
            button.setBorder(null);
            button.setBackground(null);
            button.setToolTipText("加载新游戏");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    loadNewGame();
                }
            });
            toolBar.add(button);


            button = new JButton("  编辑模式  ");
            button.setBorder(null);
            button.setBackground(null);
            button.setToolTipText("切换到编辑模式");
            // when this button is pushed it calls animationWindow.setMode(false)
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    changeMode(Game_mode.BUILDING_MODE);
                    runButton.setEnabled(false);
                    gizmoBar.setVisible(true);//show tools used for editing
                }
            });
            toolBar.add(button);


            button = new JButton("  游戏模式  ");
            button.setBorder(null);
            button.setBackground(null);
            button.setToolTipText("切换到游戏模式");
            // when this button is pushed it calls animationWindow.setMode(false)
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    changeMode(Game_mode.RUNNING_MODE);
                    runButton.setEnabled(true);
                    gizmoBar.setVisible(false);//hide tools used for editing
                    operationBar.setVisible(false);
                }
            });
            toolBar.add(button);


            runButton = new JButton("  暂停  ");
            runButton.setBorder(null);
            runButton.setBackground(null);
            runButton.setToolTipText("暂停游戏");
            // when this button is pushed it calls animationWindow.setMode(false)
            runButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(runButton.getText()=="  暂停  "){
                        animationWindow.setMode(AnimationWindow.Anim_mode.STOP_MODE);
                        runButton.setText("  继续  ");
                    }
                    else{
                        animationWindow.setMode(AnimationWindow.Anim_mode.RUNNING_MODE);
                        runButton.setText("  暂停  ");
                    }
                }
            });
            toolBar.add(runButton);


            button = new JButton("  退出  ");
            button.setBorder(null);
            button.setBackground(null);
            button.setToolTipText("Quit the program");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });
            toolBar.add(button);

            toolBar.addSeparator();


            //Position Box,to show/set position,only show when "position" button is clicked
            posBox=Box.createHorizontalBox();        //set box
            posBox.setVisible(false);
            posLabel=new JLabel("   position x:   ");//add label
            posBox.add(posLabel);
            posX=new JTextField(5);                  //add text field for position x
            posX.setMaximumSize(posX.getPreferredSize());
            posBox.add(posX);
            posLabel=new JLabel("   position y:   ");//add label
            posBox.add(posLabel);
            posY=new JTextField(5);                  //add text field for position y
            posY.setMaximumSize(posY.getPreferredSize());//需要读取选中物件的位置
            posBox.add(posY);
            toolBar.add(posBox);                     //add box

            //Rate Box,to show/set position,only show when "rate" button is clicked
            rateBox=Box.createHorizontalBox();        //set box
            rateBox.setVisible(false);
            rateLabel=new JLabel("   rate x:   ");//add label
            rateBox.add(rateLabel);
            rateX=new JTextField(5);                  //add text field for position x
            rateX.setMaximumSize(rateX.getPreferredSize());
            rateBox.add(rateX);
            rateLabel=new JLabel("   rate y:   ");//add label
            rateBox.add(rateLabel);
            rateY=new JTextField(5);                  //add text field for position y
            rateY.setMaximumSize(rateY.getPreferredSize());//需要读取选中物件的速度
            rateBox.add(rateY);
            toolBar.add(rateBox);                     //add box



        }

        protected void addTools(JToolBar toolBar) {

            JButton button = null;
            toolBar.setBorderPainted(false);
            toolBar.setBackground(Color.WHITE);


            button = new JButton();
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("ball.png"));
            button.setToolTipText("小球");
            // when this button is pushed it calls animationWindow.setMode(true)
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (animationWindow.getMode()== AnimationWindow.Anim_mode.EDIT_MODE) {
                        animationWindow.setChoosedType(Gizmos.Gizmos_type.LBLOCK,true);
                        setCursor(CROSSHAIR_CURSOR);//设置自己鼠标的图标//改成相应的图形
                    }
                }
            });
            toolBar.add(button);


            button = new JButton();
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("square.png"));
            button.setToolTipText("正方形障碍物");
            // when this button is pushed it calls animationWindow.setMode(true)
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.print(e.getID());
                    if(animationWindow.getMode()== AnimationWindow.Anim_mode.EDIT_MODE) {
                        /**
                         * @杨芯芯
                         * 选中图形时调用此方法，设置类型
                         */
                        animationWindow.setChoosedType(Gizmos.Gizmos_type.SQURE,true);
                        setCursor(CROSSHAIR_CURSOR);//设置自己鼠标的图标
                    }
                }
            });
            toolBar.add(button);


            button = new JButton();
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("circle.png"));
            button.setToolTipText("圆形障碍物");
            // when this button is pushed it calls animationWindow.setMode(true)
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(animationWindow.getMode()== AnimationWindow.Anim_mode.EDIT_MODE) {
                        animationWindow.setChoosedType(Gizmos.Gizmos_type.CIRCLE,true);
                        setCursor(CROSSHAIR_CURSOR);//设置自己鼠标的图标//改成相应的图形
                    }
                }
            });
            toolBar.add(button);

            button = new JButton();
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("trangle.png"));
            button.setToolTipText("三角形障碍物");
            // when this button is pushed it calls animationWindow.setMode(true)
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.print(e.getID());
                    if(animationWindow.getMode()== AnimationWindow.Anim_mode.EDIT_MODE) {
                        animationWindow.setChoosedType(Gizmos.Gizmos_type.TRANGLE,true);
                        setCursor(CROSSHAIR_CURSOR);//设置自己鼠标的图标
                    }
                }
            });
            toolBar.add(button);



            button = new JButton();
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("leftFlipper.png"));
            button.setToolTipText("左挡板");
            // when this button is pushed it calls animationWindow.setMode(true)
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(animationWindow.getMode()== AnimationWindow.Anim_mode.EDIT_MODE) {
                        animationWindow.setChoosedType(Gizmos.Gizmos_type.FLIPPER_LEFT,true);
                        setCursor(CROSSHAIR_CURSOR);//设置自己鼠标的图标//改成相应的图形
                    }
                }
            });
            toolBar.add(button);


            button = new JButton();
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("rightFlipper.png"));
            button.setToolTipText("右挡板");
            // when this button is pushed it calls animationWindow.setMode(true)
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(animationWindow.getMode()== AnimationWindow.Anim_mode.EDIT_MODE) {
                        animationWindow.setChoosedType(Gizmos.Gizmos_type.FLIPPER_RIGHT,true);
                        setCursor(CROSSHAIR_CURSOR);//设置自己鼠标的图标//改成相应的图形
                    }
                }
            });
            toolBar.add(button);


            button = new JButton();
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("absorber.png"));
            button.setToolTipText("吸收器");
            // when this button is pushed it calls animationWindow.setMode(true)
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(animationWindow.getMode()== AnimationWindow.Anim_mode.EDIT_MODE) {
                        //animationWindow.setChoosedType(Gizmos.Gizmos_type.ABSORBOR);
                        setCursor(CROSSHAIR_CURSOR);//设置自己鼠标的图标//改成相应的图形
                    }
                }
            });
            toolBar.add(button);



            button = new JButton();
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("choose.png"));
            button.setToolTipText("选择另一物件");
            // when this button is pushed it calls animationWindow.setMode(false)
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    setCursor(DEFAULT_CURSOR);//设置自己鼠标的图标
                    /**
                     * @杨芯芯
                     * 退出新物件的添加
                     * 取消当前物件选中
                     * 具体可以运行试试
                     * 现在改参数我还没写
                     */
                    animationWindow.quitAddNewItem();
                    animationWindow.quitChoose();
                    operationBar.setVisible(false);//hide operation toolbar
                    //!!execute choosing method,as gizmo/ball is chosen,show toolbar
                }
            });
            toolBar.add(button);

        }

        /**
         * @modifies toolBar
         * @effects adds operations to gizmos/balls
         * @param toolBar toolbar to add buttons to.
         */
        protected void addOperations(final JToolBar toolBar){

            toolBar.setBorderPainted(false);
            toolBar.setBackground(Color.WHITE);

            button=new JButton();//位置
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("position.png"));
            button.setToolTipText("设置位置");//also realized by pulling
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    //toolbar1中显示位置(x+y)，label+textfield
                    posBox.setVisible(true);
                    rateBox.setVisible(false);

                }
            });
            toolBar.add(button);


            button=new JButton();//速度//only for ball and flipper
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("rate.png"));
            button.setToolTipText("设置速度");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    //toolbar1中显示速度(x+y)，并可更改，label+textfield
                    rateBox.setVisible(true);
                    posBox.setVisible(false);

                }
            });
            toolBar.add(button);


            button=new JButton();//旋转
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("rotate.png"));
            button.setToolTipText("顺时针旋转90°");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    //对选中的图形进行10°旋转
                    //后续：在toolbar1中显示旋转角度（可修改）
                    oldChoosedGizmos.setScare(oldChoosedGizmos.getScare()*1.1f);
                    oldChoosedGizmos.setRotation(oldChoosedGizmos.getRotation() - 10.0f);
                }
            });
            toolBar.add(button);


            button=new JButton();//连接
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("connect.png"));
            button.setToolTipText("给选中物件添加触发器");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    //已有选中的gizmo
                    //选中另一个匹配的gizmo
                    //对两个gizmo连接
                    if(oldChoosedGizmos != null){
                        animationWindow.queryConnectedGizmos(true);
                    }
                }
            });
            toolBar.add(button);


            button=new JButton();//删除
            button.setBorderPainted(false);
            button.setBackground(null);
            button.setIcon(new ImageIcon("delete.png"));
            button.setToolTipText("删除选中小球/物件");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    //对选中的gizmo/小球进行删除
                    animationWindow.deleteGizmosById(oldChoosedGizmos.getGizmosID());
                    animationWindow.quitChoose();
                    operationBar.setVisible(false);//hide operation bar
                    posBox.setVisible(false);//hide box of position and rate
                    rateBox.setVisible(false);
                }
            });
            toolBar.add(button);

        }

        private void showDrawingArea(){

        }

        private void changeMode(Game_mode game_mode){
            switch (game_mode){
                case BUILDING_MODE:
                    animationWindow.setMode(AnimationWindow.Anim_mode.EDIT_MODE);
                    break;
                case RUNNING_MODE:
                    animationWindow.setMode(AnimationWindow.Anim_mode.RUNNING_MODE);
                    break;
            }
        }


        /**
         * 从xml文件中读取所有的Gizmos
         * 此处是假数据，请 @张颖 补全
         * @return
         */
        private ArrayList<Gizmos> getAllGizmosFromXml(){
            ArrayList<Gizmos> test = new ArrayList<Gizmos>();

            try {
                File file = new File("new.xml");
                SAXReader reader = new SAXReader();
                Document doc = reader.read(file);

                Element root=doc.getRootElement();
                for (Iterator iter = root.elementIterator("gizmos"); iter.hasNext();) {
                    Element element = (Element) iter.next();
                    for (Iterator iter2 = element.elementIterator("squareBumper"); iter2.hasNext();) {
                        Element element2 = (Element) iter2.next();
                        Attribute sb_nameAttr=element2.attribute("name");
                        String sb_name=sb_nameAttr.getValue();
                        Attribute sb_pxAttr=element2.attribute("x");
                        String sb_px=sb_pxAttr.getValue();
                        Attribute sb_pyAttr=element2.attribute("y");
                        String sb_py=sb_pyAttr.getValue();
                        float posXFromXML = Float.parseFloat(sb_px);  //现在此值真的是从xml文件里取出来的
                        float posYFromXML =  Float.parseFloat(sb_py);  //现在此值真的是从xml文件里取出来的
                        float width = 20;
                        float height = 20;
                        String gizmosId =sb_name;
                        Squre squre1 = new Squre(animationWindow,posXFromXML,posYFromXML,width,height);
                        squre1.setGizmosID(gizmosId);
                        squre1.setType(Gizmos.Gizmos_type.SQURE);
                        test.add(squre1);
                    }
                    for (Iterator iter2 = element.elementIterator("circleBumper"); iter2.hasNext();) {
                        Element element2 = (Element) iter2.next();
                        Attribute sb_nameAttr=element2.attribute("name");
                        String sb_name=sb_nameAttr.getValue();
                        Attribute sb_pxAttr=element2.attribute("x");
                        String sb_px=sb_pxAttr.getValue();
                        Attribute sb_pyAttr=element2.attribute("y");
                        String sb_py=sb_pyAttr.getValue();
                        float posXFromXML = Float.parseFloat(sb_px);  //现在此值真的是从xml文件里取出来的
                        float posYFromXML =  Float.parseFloat(sb_py);  //现在此值真的是从xml文件里取出来的
                        float radius = 35/2;
                        String gizmosId =sb_name;
                        Circle circle1 = new Circle(animationWindow,posXFromXML,posYFromXML,radius);
                        circle1.setGizmosID(gizmosId);
                        circle1.setType(Gizmos.Gizmos_type.CIRCLE);
                        test.add(circle1);
                    }
                    for (Iterator iter2 = element.elementIterator("triangleBumper"); iter2.hasNext();) {
                        Element element2 = (Element) iter2.next();
                        Attribute sb_nameAttr=element2.attribute("name");
                        String sb_name=sb_nameAttr.getValue();
                        Attribute sb_pxAttr=element2.attribute("x");
                        String sb_px=sb_pxAttr.getValue();
                        Attribute sb_pyAttr=element2.attribute("y");
                        String sb_py=sb_pyAttr.getValue();
                        float posXFromXML = Float.parseFloat(sb_px);  //现在此值真的是从xml文件里取出来的
                        float posYFromXML =  Float.parseFloat(sb_py);  //现在此值真的是从xml文件里取出来的
                        float baseLength = 35;
                        float pointAngleX = baseLength/2;
                        float pointAngleY = baseLength;
                        String gizmosId =sb_name;
                        Triangular triangle = new Triangular(animationWindow,posXFromXML,posYFromXML,baseLength, pointAngleX,pointAngleY);
                        triangle.setGizmosID(gizmosId);
                        triangle.setType(Gizmos.Gizmos_type.TRANGLE);
                        test.add(triangle);
                    }
                    for (Iterator iter2 = element.elementIterator("leftFlipper"); iter2.hasNext();) {
                        Element element2 = (Element) iter2.next();
                        Attribute sb_nameAttr=element2.attribute("name");
                        String sb_name=sb_nameAttr.getValue();
                        Attribute sb_pxAttr=element2.attribute("x");
                        String sb_px=sb_pxAttr.getValue();
                        Attribute sb_pyAttr=element2.attribute("y");
                        String sb_py=sb_pyAttr.getValue();
                        float posXFromXML = Float.parseFloat(sb_px);  //现在此值真的是从xml文件里取出来的
                        float posYFromXML =  Float.parseFloat(sb_py);  //现在此值真的是从xml文件里取出来的
                        float height = 10;
                        float width = 35*2;
                        String gizmosId =sb_name;
                        Flipper lfliper = new Flipper(animationWindow,posXFromXML,posYFromXML, width,height, Flipper.Flipper_type.LEFT);
                        lfliper.setGizmosID(gizmosId);
                        lfliper.setType(Gizmos.Gizmos_type.FLIPPER_LEFT);
                        test.add(lfliper);
                    }

                    for (Iterator iter2 = element.elementIterator("rightFlipper"); iter2.hasNext();) {
                        Element element2 = (Element) iter2.next();
                        Attribute sb_nameAttr=element2.attribute("name");
                        String sb_name=sb_nameAttr.getValue();
                        Attribute sb_pxAttr=element2.attribute("x");
                        String sb_px=sb_pxAttr.getValue();
                        Attribute sb_pyAttr=element2.attribute("y");
                        String sb_py=sb_pyAttr.getValue();
                        float posXFromXML = Float.parseFloat(sb_px);  //现在此值真的是从xml文件里取出来的
                        float posYFromXML =  Float.parseFloat(sb_py);  //现在此值真的是从xml文件里取出来的
                        float height = 10;
                        float width = 35*2;
                        String gizmosId =sb_name;
                        Flipper rfliper = new Flipper(animationWindow,posXFromXML,posYFromXML, width,height, Flipper.Flipper_type.RIGHT);
                        rfliper.setGizmosID(gizmosId);
                       rfliper.setType(Gizmos.Gizmos_type.FLIPPER_RIGHT);
                        test.add(rfliper);
                    }
                }

            } catch (Exception e) {
                System.out.println("Can't read the file");
            }


         /*   float posXFromXML = 200;  //假装此值是从xml文件里取出来的
            float posYFromXML = 190;  //假装此值是从xml文件里取出来的
            float width = 20;
            float height = 20;
            String gizmosId = "S01";
            Squre squre1 = new Squre(animationWindow,posXFromXML,posYFromXML,width,height);
            squre1.setGizmosID(gizmosId);
            squre1.setType(Gizmos.Gizmos_type.SQURE);
            test.add(squre1);

            float posXFromXML2 = 100;  //假装此值是从xml文件里取出来的
            float posYFromXML2 = 130;  //假装此值是从xml文件里取出来的
            float width2 = 20;
            float height2 = 20;
            String gizmosId2 = "S02";
            Squre squre12 = new Squre(animationWindow,posXFromXML2,posYFromXML2,width2,height2);
            squre12.setGizmosID(gizmosId);
            squre12.setType(Gizmos.Gizmos_type.SQURE);
            test.add(squre12);  */
            //System.out.println(test.size());
            return test;
        }

        /**
         * 此处也是假数据
         * 请 @张颖 从XML中解析出小球参数
         * @return
         */
        private BouncingBall getBallFromXml(){
            BouncingBall testBall=new BouncingBall(animationWindow);
            try {
                File file = new File("new.xml");
                SAXReader reader = new SAXReader();
                Document doc = reader.read(file);

                Element root=doc.getRootElement();
                for (Iterator iter = root.elementIterator("ball"); iter.hasNext();) {
                    Element element = (Element) iter.next();//不知道不用迭代器怎么写，所以虽然只有一个Ball也用了迭代。
                    Attribute b_nameAttr=element.attribute("name");
                    String b_name=b_nameAttr.getValue();
                    Attribute b_pxAttr=element.attribute("x");
                    String b_px=b_pxAttr.getValue();
                    Attribute b_pyAttr=element.attribute("y");
                    String b_py=b_pyAttr.getValue();
                    Attribute b_vxAttr=element.attribute("xVelocity");
                    String b_vx=b_vxAttr.getValue();
                    Attribute b_vyAttr=element.attribute("yVelocity");
                    String b_vy=b_vyAttr.getValue();
                    float posX =Float.parseFloat(b_px);
                    float posY = Float.parseFloat(b_py);
                    float vx =Float.parseFloat(b_vx);
                    float vy = Float.parseFloat(b_vy);
                    testBall = new BouncingBall(animationWindow,posX,posY,vx,vy);
                }

            } catch (Exception e) {
                System.out.println("Can't read the file");
            }

            //  BouncingBall testBall = new BouncingBall(animationWindow,posX,posY,vx,vy);
            System.out.println(testBall.getBallCenterPos().getX());
            return testBall;

        }

        /**
         * 将所有gizmos信息和小球信息存入xml
         * @张颖 补全
         * @param gizmoses
         * @param ball
         */
        private void saveGameStateIntoXML(ArrayList<Gizmos> gizmoses, BouncingBall ball){
            Document doc = DocumentHelper.createDocument();
            doc.addProcessingInstruction("xml-stylesheet", "type='text/xsl ");
            Element root = doc.addElement("board");


            //ball
            Element bouncingball=root.addElement("ball");
            bouncingball.addAttribute("name", "Ball");
            double px=ball.getBallCenterPos().getX();
            double py=ball.getBallCenterPos().getY();
            double vx=ball.getVx();
            double vy=ball.getVy();
            bouncingball.addAttribute("x", String.valueOf(px));
            bouncingball.addAttribute("y", String.valueOf(py));
            bouncingball.addAttribute("xVelocity",String.valueOf(vx));
            bouncingball.addAttribute("yVelocity", String.valueOf(vy));


            //Gizmo
            Element gizmos=root.addElement("gizmos");
            Iterator<Gizmos> it=gizmoses.iterator();
          // System.out.println(gizmoses.size());
            while(it.hasNext()){
                Gizmos currentGizmos = it.next();
                Gizmos.Gizmos_type gt=currentGizmos.getType();
              //  System.out.println(gt==Gizmos.Gizmos_type.SQURE);
                String gizID=currentGizmos.getGizmosID();
                double g_px=currentGizmos.getPostion().getX();
                System.out.println(g_px);
                double g_py=currentGizmos.getPostion().getY();
                if(gt==Gizmos.Gizmos_type.SQURE)
                {
                    Element squareBumper=gizmos.addElement("squareBumper");
                    squareBumper.addAttribute("name",gizID);
                    squareBumper.addAttribute("x", String.valueOf(g_px));
                    squareBumper.addAttribute("y", String.valueOf(g_py));
                }
                else if(gt==Gizmos.Gizmos_type.CIRCLE)
                {
                    Element circleBumper=gizmos.addElement("circleBumper");
                    circleBumper.addAttribute("name",gizID);
                    circleBumper.addAttribute("x", String.valueOf(g_px));
                    circleBumper.addAttribute("y",  String.valueOf(g_py));
                }
                else if(gt==Gizmos.Gizmos_type.TRANGLE)
                {
                    Element triangleBumper=gizmos.addElement("triangleBumper");
                    triangleBumper.addAttribute("name",gizID);
                    triangleBumper.addAttribute("x",String.valueOf(g_px));
                    triangleBumper.addAttribute("y",  String.valueOf(g_py));
                }
                else if(gt==Gizmos.Gizmos_type.FLIPPER_LEFT)
                {
                    Element triangleBumper=gizmos.addElement("leftFlipper");
                    triangleBumper.addAttribute("name",gizID);
                    triangleBumper.addAttribute("x",String.valueOf(g_px));
                    triangleBumper.addAttribute("y",  String.valueOf(g_py));
                }
                else if(gt==Gizmos.Gizmos_type.FLIPPER_RIGHT)
                {
                    Element triangleBumper=gizmos.addElement("rightFlipper");
                    triangleBumper.addAttribute("name",gizID);
                    triangleBumper.addAttribute("x",String.valueOf(g_px));
                    triangleBumper.addAttribute("y",  String.valueOf(g_py));
                }
                else  //absorber
                {
                    Element triangleBumper=gizmos.addElement("absorber");
                    triangleBumper.addAttribute("name",gizID);
                    triangleBumper.addAttribute("x",String.valueOf(g_px));
                    triangleBumper.addAttribute("y",  String.valueOf(g_py));
                }
            }


            //connection
            Element connections=root.addElement("connections");
            //假装这里有个循环，虽然现在不知道参数怎么传过来
            Element connect=connections.addElement("connect");
            connect.addAttribute("sourceGizmo", "aaaaa");
            connect.addAttribute("targetGizmo", "bbbbb");


            try {
                OutputFormat format = new OutputFormat("    ", true);
                format.setEncoding("ISO-8859-1");
                XMLWriter xmlWriter = new XMLWriter(new PrintWriter(new FileOutputStream("new.xml")), format);
                xmlWriter.write(doc);
                xmlWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        /**
         * 更新animationWindow的状态，加载新游戏
         */
        private void loadNewGame(){
            ArrayList<Gizmos> newGizmos = getAllGizmosFromXml();
            BouncingBall newBall = getBallFromXml();
            animationWindow.refreashWindow(newGizmos,newBall);
        }

        /**
         * 保存游戏
         */
        private void saveGame(){
            ArrayList<Gizmos> gizmoses = animationWindow.getAllGizmos();
            BouncingBall ball = animationWindow.getBall();
            saveGameStateIntoXML(gizmoses,ball);
        }
    }
}
